#!/l/python2.6/bin/python

import cgi
import cgitb
import glob
import os
import sys
import autograder

import templates
from makedatetime import makedatetime
import datetime
import problem
import submissions

def problembox(prob):
    """Builds the chunk of HTML that displays one problem."""
    assert isinstance(prob,problem.Problem)

    username = str(os.environ["REMOTE_USER"]).split('@')[0]
    status = prob.getstatus()

    if status == "unreleased":
        return ""
    elif status == "closed":
        # would it be better if we showed the box from the results page here
        # instead?
        template_closed = templates.loadtemplate("problembox-closed")
        return template_closed.substitute(PROBLEM=prob.name,
                                          TEXT=prob.description,
                                          STATUS=status,
                                          SAMPLE=prob.solution)
    elif status == "overtime":
        #problem is in overtime!!
        template_open = templates.loadtemplate("problembox")
        return template_open.substitute(PROBLEM=prob.name,
                                        DUE=prob.duetime,
                                        STATUS=status,
                                        TEXT=prob.description)
    elif submissions.already_submitted(username, prob.name):
        template = templates.loadtemplate("problembox-submitted")
        return template.substitute(PROBLEM=prob.name,
                                   DUE=prob.duetime,
                                   TEXT=prob.description,
                                   STATUS=status)
    else:
        #problem is still open, show and allow upload box
        template_open = templates.loadtemplate("problembox")
        return template_open.substitute(PROBLEM=prob.name,
                                        DUE=prob.duetime,
                                        STATUS=status,
                                        TEXT=prob.description)

def main():
    data = cgi.FieldStorage();
    template = templates.loadtemplate("problems")
    problems = problem.list_problems()

    problemboxes_lst = map(problembox, problems)
    problemboxes = "\n".join(problemboxes_lst)

    print "Content-type: text/html\n"
    print template.substitute(PROBLEMBOXES=problemboxes)

if __name__ == "__main__": main()
